package com.xlhj.yucloud.web.service;

import com.xlhj.yucloud.entity.SysUserInfo;
import com.xlhj.yucloud.service.SysUserInfoService;
import com.xlhj.yucloud.web.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * @author: liucaijing
 * @description: 登录业务接口实现类
 * @date: 2021/9/10 14:25
 */
@Component
public class LoginService {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private SysUserInfoService userInfoService;

    public String login(String userName, String password) {
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userName, password));
        } catch (Exception e) {
            e.printStackTrace();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return tokenService.generateToken(loginUser.getUserId(), loginUser.getUsername());
    }

    /**
     * 获取当前用户信息
     * @return
     */
    public SysUserInfo getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = (String) authentication.getPrincipal();
        SysUserInfo userInfo = userInfoService.findUserByUserName(username);
        return userInfo;
    }
}
